from flask import Blueprint, render_template, request
from flask import Blueprint, request, render_template, jsonify, current_app
from applications.common.curd import model_to_dicts, enable_status, disable_status
from applications.common.helper import ModelFilter
from applications.extensions import db
from applications.common.utils import upload as upload_curd

from applications.common.utils.http import table_api, fail_api, success_api
from applications.models import Models

model_test_bp = Blueprint('modeltest', __name__, url_prefix='/admin/model_test')

@model_test_bp.get('/')
# @authorize("admin:model_test", log=True)
def modeltest_main():
    return render_template('admin/model_test/model.html')

#  图片数据
@model_test_bp.get('/table')
# @authorize("admin:model_test", log=True)
def table():
    page = request.args.get('page', type=int)
    limit = request.args.get('limit', type=int)

    data, count = upload_curd.get_model(page=page, limit=limit)
    return table_api(data=data, count=count)


#   上传
@model_test_bp.get('/upload')
# @authorize("admin:model_test", log=True)
def upload():
    return render_template('admin/model_test/model_add.html')


#   上传接口
@model_test_bp.post('/upload')
# @authorize("admin:model_test", log=True)
def upload_api():
    if 'file' in request.files:
        model = request.files['file']
        mime = request.files['file'].content_type

        file_url = upload_curd.upload_model(model=model, mime=mime)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {"src": file_url}
        }
        return jsonify(res)
    return fail_api()
#
#
# #    图片删除
# @admin_file.route('/delete', methods=['GET', 'POST'])
# @authorize("admin:file:delete", log=True)
# def delete():
#     _id = request.form.get('id')
#     res = upload_curd.delete_photo_by_id(_id)
#     if res:
#         return success_api(msg="删除成功")
#     else:
#         return fail_api(msg="删除失败")
#
#
# # 图片批量删除
# @admin_file.route('/batchRemove', methods=['GET', 'POST'])
# @authorize("admin:file:delete", log=True)
# def batch_remove():
#     ids = request.form.getlist('ids[]')
#     photo_name = Photo.query.filter(Photo.id.in_(ids)).all()
#     upload_url = current_app.config.get("UPLOADED_MODELS_DEST")
#     for p in photo_name:
#         os.remove(upload_url + '/' + p.name)
#     photo = Photo.query.filter(Photo.id.in_(ids)).delete(synchronize_session=False)
#     db.session.commit()
#     if photo:
#         return success_api(msg="删除成功")
#     else:
#         return fail_api(msg="删除失败")